import os
import sys
import time
from playwright.sync_api import sync_playwright
import re
import pyperclip

test = True
answer_index = 0


_xp = None
p = None
browser = None
page = None
el_input = None
el_send = None
pwd = 'D:/eglwa/home/apnews'
personal_data_path = r'C:\Users\eglwa\AppData\Local\Microsoft\Edge\User Data Work'
chat_url = 'https://chat.openai.com/'
input_xpath = '//*[@id="prompt-textarea"]'
send_button_xpath = '//*[@id="__next"]//main/div/div[2]/form/div/div[2]/div/button'
copy_content_xpath = '//*[@id="__next"]//main/div/div[1]/div/div/div/div[{}]/div/div[2]/div[2]/div/button'
continue_generate_xpath = '//*[@id="__next"]/div[1]/div[2]/div/main/div[3]/form/div/div[1]/div/button[2]'


def start():
    global _xp, p, browser, page, el_input, el_send
    _xp = sync_playwright()
    p = _xp.__enter__()
    browser = p.chromium.launch_persistent_context(
        channel='msedge', user_data_dir=personal_data_path, headless=not test)
    page = browser.new_page()
    page.add_init_script(
        'Object.defineProperty(navigator, "webdriver", {get: () => undefined})')
    page.goto(chat_url)
    el_input = page.locator(input_xpath)
    el_send = page.locator(send_button_xpath)
    browser.set_default_timeout(60*1000)


def make_a_question(question):
    global answer_index
    el_input.fill(question)
    el_send.click()
    answer_index += 2
    copy_content_xpath = copy_content_xpath.format(answer_index)
    el_copy = page.locator(copy_content_xpath)
    el_copy.click()
    continue_el = page.query_selector(continue_generate_xpath)
    if continue_el:
        continue_el.click()
        el_copy = page.locator(copy_content_xpath)
    el_copy.click()
    answer = pyperclip.paste()
    return answer

def new_topic():
    global answer_index
    close(False)
    new_topic_btn_xpath = '//*[@id="__next"]/div[1]/div[1]/div/div/div/nav/div[1]/a'
    page.locator(new_topic_btn_xpath).click()
    answer_index = 0

def close(exit=True):
    # delete session
    session_xpath = '//*[@id="__next"]/div[1]/div[1]/div/div/div/nav/div[3]/div/div/span[1]/div[1]/ol/li[1]'
    delete_session_xpath = '//*[@id="__next"]/div[1]/div[1]/div/div/div/nav/div[3]/div/div/span[1]/div[1]/ol/li[1]/a/div[2]/button[3]'
    confirm_xpath = '//*[@id="__next"]/div[1]/div[1]/div/div/div/nav/div[3]/div/div/span[1]/div[1]/ol/li[1]/a/div[2]/button[1]'
    page.locator(session_xpath).click()
    page.locator(delete_session_xpath).click()
    page.locator(confirm_xpath).click()
    if not exit:
        return
    # close browser
    quit()

def quit():
    browser.close()
    _xp.__exit__(None, None, None)

if __name__ == '__main__':
    start()
    while 1:
        x = input('>>')
        if x == 'q':
            break
        if not x:
            continue
        answer = make_a_question(x)
        print(answer)
    close()
